﻿using MaterialDesignColors;
using MaterialDesignThemes.Wpf;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using RevitAddInDeployer;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using ZhuXingFamilys.ExportExcel.entity;
using ZhuXingFamilys.ExportExcel.utils;
using ZhuXingFamilys.Help;

namespace ZhuXingFamilys.ExportExcel
{
    public delegate void RulesChangeHandler();
    /// <summary>
    /// RulesWindow.xaml 的交互逻辑
    /// </summary>
    public partial class RulesWindow : Window
    {
        public event RulesChangeHandler RulesChangeEvent;
        // 规则树节点数据
        private RulesNode rulesNodes = null;
        // 详细规则数据
        private List<Rules> rulesList = new List<Rules>();
        // 相关规则数据
        private List<Rules> ruleListForDependence = new List<Rules>();
        // 规则选中项
        // string cellComboBoxSelectedValue = null;
        private Rules comboBoxSelectedRule = new Rules();
        // 清单规则树
        private List<RulesNode> rulesNodeList = new List<RulesNode>();
        // 最终保存数据
        private List<Rules> li = null;
        // 当前用户
        private string userName;
        // 规则是否修改了
        private bool isChange = false;
        // 当前页规则是否修改了
        private bool isCurrenRuleChange = false;
        // 规则文件路径
        private string RulesDataBasePath = string.Empty;
        // 规则文件名称
        private string RulesDataBaseFileName = "RulesDataBase.xls";
        public RulesWindow(string userName)
        {
            //ui库使用
            ColorZoneAssist.SetMode(new GroupBox(), ColorZoneMode.Light);
            Hue hue = new Hue("name", System.Windows.Media.Color.FromArgb(1, 2, 3, 4), System.Windows.Media.Color.FromArgb(1, 5, 6, 7));
            //this.rulesNodes = rulesNode;
            //this.rulesList = rulesNode.rulesList;
            //RulesTree rt = new RulesTree(userName);
            //this.rulesList = rt.getRules(rulesNode.NodeID);
            // 获取规则文件路径
            RulesDataBasePath = Path.Combine(Set.getaddress(), RulesDataBaseFileName);
            this.userName = userName;
            InitializeComponent();
        }
        // 窗口加载完成
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            bool flag = File.Exists(RulesDataBasePath);
            if (!flag)
            {
                MessageBox.Show("未检测到配置文件，即将开始从服务器下载默认配置文件", "提示", MessageBoxButton.OK);
                downloadRules();
                this.Close();
            }
            rulesInitialization();

            if (RulesNodeTreeView.Items.Count != 0)
            {
                // 展开第一个
                RulesNode ti = RulesNodeTreeView.Items[0] as RulesNode;
                DependencyObject dObject = RulesNodeTreeView.ItemContainerGenerator.ContainerFromItem(ti);
                ((TreeViewItem)dObject).IsExpanded = true;
            }
        }
        // 初始化
        private void rulesInitialization()
        {
            // 加载清单规则
            try
            {
                RulesTree rt = new RulesTree(userName);
                rulesNodeList = rt.builTree();

                // 备份原规则文件
                if (File.Exists(RulesDataBasePath + "_bak"))
                {
                    File.Delete(RulesDataBasePath + "_bak");
                }
                File.Copy(RulesDataBasePath, RulesDataBasePath + "_bak");

            }
            catch (Exception e3)
            {
                if (e3.Message.Contains("另一进程使用"))
                {
                    MessageBox.Show(e3.Message, "提示");
                }
                else if (e3.Message.Contains("未将对象引用设置到对象的实例"))
                {
                    MessageBox.Show("数据库文件错误", "提示");
                }
                else
                {
                    MessageBox.Show("加载失败，原因：" + e3.Message, "提示");
                }
            }
            RulesNodeTreeView.ItemsSource = rulesNodeList;
        }

        // 规则清单树点击事件
        private void RulesNodeTreeView_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            //if (RulesNodeTreeView.SelectedItem is RulesNode)
            //{
            //	RulesNode rulesNode = RulesNodeTreeView.SelectedItem as RulesNode;
            //	if (rulesNode != null && rulesNode.Level == 2)
            //	{
            //		RulesTree rt = new RulesTree(userName);
            //		this.rulesList = rt.getRules(rulesNode.NodeID);
            //		//rulesList = new List<Rules>();
            //		//var lss = rulesNodeList.Where(r => r.NodeID == rulesNode.ParentID).ToList();
            //		//foreach (var item in lss)
            //		//{
            //		//	foreach(var ruless in item.Children)
            //		//	{
            //		//		if(ruless.NodeID == rulesNode.NodeID)
            //		//		{
            //		//			rulesList.AddRange(ruless.rulesList);
            //		//		}
            //		//	}

            //		//}

            //		// 标题
            //		this.rulesTitle.Text = rulesNode.Name + "清单规则详细设置";
            //		// 生成规则视图展示数据
            //		getRulesListforView();
            //		this.ListView1.ItemsSource = rulesListforView;
            //	}
            //}
        }
        // 规则树选项改变
        private void RulesNodeTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            // 改变后的数据
            saveCurrentRulesList();

            if (RulesNodeTreeView.SelectedItem is RulesNode)
            {
                RulesNode rulesNode = RulesNodeTreeView.SelectedItem as RulesNode;
                if (rulesNode != null && rulesNode.Level == 3)
                {
                    RulesTree rt = new RulesTree(userName);
                    this.rulesList = rt.getRules(rulesNode.NodeID);

                    // this.rulesList = rulesNode.rulesList;
                    // 标题
                    this.rulesTitle.Text = rulesNode.Name + "清单规则详细设置";
                    // 生成规则视图展示数据
                    List<Rules> rulesListforView = getRulesListforView(rulesList);
                    this.ListView1.ItemsSource = rulesListforView;
                }
            }
            // 清空相关规则
            this.ListView2.ItemsSource = null;

        }
        // 导入导出默认
        private void Rules_Import_Export(object sender, RoutedEventArgs e)
        {
            if (e.Source is Button)
            {
                Button b = e.Source as Button;
                // 导入逻辑
                if ("导入".Equals(b.Content))
                {
                    System.Windows.Forms.OpenFileDialog fie = new System.Windows.Forms.OpenFileDialog();
                    fie.Title = "导入清单规则";
                    fie.Filter = "筑星规则|*.zx";
                    //用户点击打开后执行的逻辑
                    if (fie.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        string filePath = fie.FileName;
                        try
                        {
                            HandleFiles.DecryptFile(filePath, RulesDataBasePath);
                            MessageBox.Show("导入成功,请重新打开规则窗口", "提示");
                            this.Close();
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("文件错误,请选择正确的筑星规则文件", "提示 :");
                        }
                    }
                }
                // 导出逻辑
                if ("导出".Equals(b.Content))
                {
                    System.Windows.Forms.SaveFileDialog s = new System.Windows.Forms.SaveFileDialog();
                    s.Filter = "筑星规则|*.zx";
                    s.Title = "导出清单规则";
                    s.DefaultExt = "筑星规则|*.zx";
                    //获取文默认件扩展名
                    // string str = s.DefaultExt;
                    //用户点击"保存"后执行的逻辑
                    if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        //获取保存的目录
                        string fileName = s.FileName;
                        HandleFiles.EncryptFile(RulesDataBasePath, fileName);
                    }
                }
                // 恢复默认逻辑
                if ("默认".Equals(b.Content))
                {
                    MessageBoxResult mr = MessageBox.Show("此操作将从服务器下载默认配置，确定吗？", "提示", MessageBoxButton.OKCancel);
                    if (mr == MessageBoxResult.OK)
                    {
                        downloadRules();
                        this.Close();
                    }
                }
            }
        }
        // 下载/初始化规则
        private void downloadRules()
        {
            try
            {
                string ftpPath = @"ftp://" + "8.142.144.242/rules/";
                string rulesDefaultName = "RulesDefault.zx";
                string rulesDefaultPath = Set.getaddress();
                try
                {
                    FtpHelper.Download(rulesDefaultPath + rulesDefaultName, ftpPath + rulesDefaultName);
                }
                catch (Exception)
                {
                    MessageBox.Show("服务器连接失败，请检查网络。");
                }
                HandleFiles.DecryptFile(rulesDefaultPath + rulesDefaultName, RulesDataBasePath);
                MessageBox.Show("初始化成功,请重新打开规则窗口", "提示");
                File.Delete(rulesDefaultPath + rulesDefaultName);
            }
            catch (Exception)
            {
                MessageBox.Show("初始化失败", "提示");
                throw;
            }
        }

        // 生成规则视图展示数据
        private List<Rules> getRulesListforView(List<Rules> list)
        {
            // 规则视图展示数据
            List<Rules> list1 = new List<Rules>();
            if (list != null)
            {
                // 处理rulesList原始数据
                foreach (Rules rules in list)
                {
                    // 如果是当前选择的规则
                    if (rules.IsSelected == 1)
                    {
                        if (!list1.Contains(rules))
                        {
                            List<string> OptDescList = new List<string>();
                            OptDescList.Add(rules.OptDesc);
                            rules.OptDescList = OptDescList;
                            rules.SelectedOptDesc = rules.OptDesc;
                            list1.Add(rules);
                        }
                        else
                        {
                            foreach (Rules rul in list1)
                            {
                                if (rul.Equals(rules))
                                {
                                    list1.Remove(rul);
                                    List<string> l1 = new List<string>();
                                    if (rul.OptDescList != null)
                                    {
                                        l1 = rul.OptDescList;
                                    }
                                    l1.Add(rules.OptDesc);
                                    rul.OptDescList = l1;
                                    rul.SelectedOptDesc = rules.OptDesc;
                                    list1.Add(rul);
                                    break;
                                }
                            }
                        }

                    }
                    // 如果不是当前选择的规则
                    else
                    {
                        if (!list1.Contains(rules))
                        {
                            List<string> OptDescList = new List<string>();
                            OptDescList.Add(rules.OptDesc);
                            rules.OptDescList = OptDescList;
                            list1.Add(rules);
                        }
                        else
                        {
                            foreach (Rules rul in list1)
                            {
                                if (rul.Equals(rules))
                                {
                                    list1.Remove(rul);
                                    List<string> l1 = new List<string>();
                                    if (rul.OptDescList != null)
                                    {
                                        l1 = rul.OptDescList;
                                    }
                                    l1.Add(rules.OptDesc);
                                    rul.OptDescList = l1;
                                    list1.Add(rul);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            return list1;
        }

        // 规则选项切换
        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var cb = (sender as System.Windows.Controls.ComboBox);
            if (cb.IsLoaded)
            {
                comboBoxSelectedRule = cb.DataContext as Rules;
                // 动态赋值
                if (cb.SelectedValue != null)
                {
                    string selectedValue = cb.SelectedValue.ToString();
                    comboBoxSelectedRule.SelectedOptDesc = selectedValue;
                    //this.cellComboBoxSelectedValue = selectedValue;
                    Rules r1 = rulesList.Where(r => r.RuleID == comboBoxSelectedRule.RuleID).FirstOrDefault();
                    if (r1 != null)
                    {
                        int index = rulesList.IndexOf(r1);
                        rulesList.Remove(r1);

                        comboBoxSelectedRule.Change = true;
                        rulesList.Insert(index, comboBoxSelectedRule);

                    }
                    isCurrenRuleChange = true;
                }
            }
        }
        // 保存逻辑
        private void saveCurrentRulesList()
        {
            try
            {
                if (isCurrenRuleChange && rulesList != null && rulesList.Count != 0)
                {
                    string path = RulesDataBasePath;
                    string fileName = RulesDataBaseFileName;
                    // 加载Excel
                    IWorkbook workbook;
                    // 读
                    using (FileStream fileStream = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
                    {
                        byte[] bytes = new byte[fileStream.Length];
                        fileStream.Read(bytes, 0, bytes.Length);
                        // 把 byte[] 转换成 Stream
                        MemoryStream stream = new MemoryStream(bytes);
                        // 格式判断
                        if (fileName.EndsWith(".xlsx"))
                        {
                            workbook = new XSSFWorkbook(stream);
                        }
                        else
                        {
                            workbook = new HSSFWorkbook(stream);
                        }
                        // 读取Rules页
                        ISheet sheet = workbook.GetSheetAt(1);
                        // 遍历所有行
                        IEnumerator rows = sheet.GetRowEnumerator();
                        // 标题行
                        rows.MoveNext();
                        // 更新
                        while (rows.MoveNext())
                        {
                            IRow row = (IRow)rows.Current;
                            ICell RuleID = row.GetCell(0);
                            ICell NodeID = row.GetCell(1);
                            ICell OptDesc = row.GetCell(5);
                            ICell IsSelected = row.GetCell(6);
                            // 更新规则
                            foreach (Rules r in rulesList)
                            {
                                if (int.Parse(RuleID.ToString()) == r.RuleID && int.Parse(NodeID.ToString()) == r.NodeID)
                                {
                                    IsSelected.SetCellValue(0);
                                    break;
                                }
                            }
                            // 更新相关规则
                            foreach (Rules r in ruleListForDependence)
                            {
                                if (int.Parse(RuleID.ToString()) == r.RuleID && int.Parse(NodeID.ToString()) == r.NodeID)
                                {
                                    IsSelected.SetCellValue(0);
                                    break;
                                }
                            }
                        }

                        // 更新
                        rows.Reset();
                        rows.MoveNext();
                        while (rows.MoveNext())
                        {
                            IRow row = (IRow)rows.Current;
                            ICell RuleID = row.GetCell(0);
                            ICell NodeID = row.GetCell(1);
                            ICell OptDesc = row.GetCell(5);
                            ICell IsSelected = row.GetCell(6);
                            // 更新规则
                            foreach (Rules r in rulesList)
                            {
                                if (int.Parse(RuleID.ToString()) == r.RuleID && int.Parse(NodeID.ToString()) == r.NodeID && OptDesc.ToString() == r.SelectedOptDesc)
                                {
                                    IsSelected.SetCellValue(1);
                                    break;
                                }
                            }
                            // 更新相关规则
                            foreach (Rules r in ruleListForDependence)
                            {
                                if (int.Parse(RuleID.ToString()) == r.RuleID && int.Parse(NodeID.ToString()) == r.NodeID && OptDesc.ToString() == r.SelectedOptDesc)
                                {
                                    IsSelected.SetCellValue(1);
                                    break;
                                }
                            }
                        }
                        fileStream.Close();
                        //workbook.Close();
                    }

                    // 写
                    using (var wook = new FileStream(path, FileMode.Create, FileAccess.Write))
                    {
                        workbook.Write(wook);
                    }
                    this.isChange = true;
                    //// 数据库
                    //string constr = "server=8.142.144.242;database=BIMDataBase;uid=sa;pwd=1qazZSE$";
                    //// SQL
                    //StringBuilder sqlstr = new StringBuilder();
                    //// 更新数据库
                    //sqlstr.Clear();
                    //sqlstr.Append("update Rules set IsSelected = 0 where RuleID = @RuleID and NodeID = @NodeID and UserName = @UserName ");
                    //SqlParameter[] p1 =
                    //{
                    //	new SqlParameter("RuleID", r.RuleID),
                    //	new SqlParameter("NodeID", r.NodeID),
                    //	new SqlParameter("UserName", userName)
                    //};
                    //SqlHelper.ExecuteNonQuery(constr, CommandType.Text, sqlstr.ToString(), p1);

                    //sqlstr.Clear();
                    //sqlstr.Append("update Rules set IsSelected = 1 ");
                    //sqlstr.Append("where RuleID = @RuleID and NodeID = @NodeID and OptDesc = @OptDesc and UserName = @UserName ");
                    //SqlParameter[] p2 =
                    //{
                    //	new SqlParameter("RuleID", r.RuleID),
                    //	new SqlParameter("NodeID", r.NodeID),
                    //	new SqlParameter("OptDesc", r.SelectedOptDesc),
                    //	new SqlParameter("UserName", userName)
                    //};
                    //SqlHelper.ExecuteNonQuery(constr, CommandType.Text, sqlstr.ToString(), p2);

                    //this.isChange = true;

                    //MessageBox.Show("保存成功", "提示");

                    isCurrenRuleChange = false;

                }
            }
            catch (Exception)
            {
                MessageBox.Show("保存失败,请检查数据库连接", "提示");
            }

        }

        // 窗口关闭
        private void Window_Closed(object sender, EventArgs e)
        {

        }
        // 确定
        private void OK_Click(object sender, RoutedEventArgs e)
        {
            saveCurrentRulesList();
            this.Close();
            MessageBoxResult r = MessageBox.Show("规则保存成功,是否开始执行扣减？", "提示", MessageBoxButton.YesNo);
            if (r == MessageBoxResult.Yes)
            {
                RulesChangeEvent();
            }

            try
            {
                File.Delete(RulesDataBasePath + "_bak");
            }
            catch (Exception exception)
            {

            }
        }

        // 取消
        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                File.Delete(RulesDataBasePath);
                File.Copy(RulesDataBasePath + "_bak", RulesDataBasePath);
                File.Delete(RulesDataBasePath + "_bak");
            }
            catch (Exception exception)
            {

            }
            this.Close();
        }
        // 相关规则展示
        private void ListView1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Rules r = ((DataGrid)e.Source).CurrentItem as Rules;
            if (r != null)
            {
                // 获取相关规则
                RulesTree rt = new RulesTree(userName);
                ruleListForDependence = rt.getDependenceRules(r);
                // 生成规则视图展示数据
                List<Rules> rulesListforView = getRulesListforView(ruleListForDependence);
                this.ListView2.ItemsSource = rulesListforView;
            }
        }
    }
}
